package com.holyn.guofang.view.distinguish;

import android.app.Activity;
import android.content.Intent;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.holyn.guofang.R;
import com.holyn.guofang.view.BaseActivity;
import com.holyn.guofang.viewcommon.popupwindow.PopupSingleSelectFromBottom;
import com.holyn.guofang.viewcommon.radiobutton.DrawableCenterRadioButton;
import com.vondear.rxtools.RxTimeUtils;
import com.vondear.rxtools.view.dialog.RxDialogWheelYearMonthDay;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Holyn on 2017/7/21.
 */

public class AlgorithmSelectActivity extends BaseActivity {
    /**
     * 对应参数SearchType
     * 查询条件类型，默认为0。例如：0（商标名称中文），1（商标名称西文）以此类推;注意：此接口部分参数时根据 普通与高级的差别而有对应拼接关系。
     */
    public static final String INTENT_KEY_ALGORITHM_MODE = "INTENT_KEY_ALGORITHM_MODE";
    /**
     * 对应参数SearchMode
     * 查询模式(0:混合 1：图形特征 2：文字内容) 备注：此参数在普通查询时，只用写死参数值为0，不需选择。
     */
    public static final String INTENT_KEY_QUERY_MODE = "INTENT_KEY_QUERY_MODE";
    public static final String INTENT_KEY_FILTER_STATE = "INTENT_KEY_QUERY_MODE";
    public static final String INTENT_KEY_DATA_TYPE = "INTENT_KEY_DATA_TYPE";
    public static final String INTENT_KEY_BEGIN_DATA = "INTENT_KEY_BEGIN_DATA";
    public static final String INTENT_KEY_END_DATA = "INTENT_KEY_END_DATA";
    public static final String INTENT_KEY_IS_SENIOR_SEARCH = "INTENT_KEY_IS_SENIOR_SEARCH";
    public static final String INTENT_KEY_TYPE_CODE_LIST = "INTENT_KEY_TYPE_CODE_LIST";
    public static final String INTENT_KEY_ALGORITHM_TYPE_LIST= "INTENT_KEY_ALGORITHM_TYPE_LIST";

    public static final int REQUEST_CODE_SELECT_ALGORITHM_TYPE_LIST = 0x0001;

    @BindView(R.id.rb_query_mode_0)
    DrawableCenterRadioButton rbQueryMode0;
    @BindView(R.id.rb_query_mode_1)
    DrawableCenterRadioButton rbQueryMode1;
    @BindView(R.id.rb_query_mode_2)
    DrawableCenterRadioButton rbQueryMode2;
    @BindView(R.id.rg_query_mode)
    RadioGroup rgQueryMode;
    @BindView(R.id.ll_query_mode)
    LinearLayout llQueryMode;
    @BindView(R.id.rb_algorithm_0)
    DrawableCenterRadioButton rbAlgorithm0;
    @BindView(R.id.rb_algorithm_1)
    DrawableCenterRadioButton rbAlgorithm1;
    @BindView(R.id.rb_algorithm_2)
    DrawableCenterRadioButton rbAlgorithm2;
    @BindView(R.id.rg_algorithm)
    RadioGroup rgAlgorithm;
    @BindView(R.id.btn_algorithm_search)
    Button btnAlgorithmSearch;
    @BindView(R.id.rb_filter_state_0)
    DrawableCenterRadioButton rbFilterState0;
    @BindView(R.id.rb_filter_state_1)
    DrawableCenterRadioButton rbFilterState1;
    @BindView(R.id.rb_filter_state_2)
    DrawableCenterRadioButton rbFilterState2;
    @BindView(R.id.rb_filter_state_3)
    DrawableCenterRadioButton rbFilterState3;
    @BindView(R.id.rg_filter_state)
    RadioGroup rgFilterState;
    @BindView(R.id.tv_filter_date_type)
    TextView tvFilterDateType;
    @BindView(R.id.tv_filter_date_begin)
    TextView tvFilterDateBegin;
    @BindView(R.id.tv_filter_date_end)
    TextView tvFilterDateEnd;
    @BindView(R.id.btn_submit)
    Button btnSubmit;

    private boolean isSeniorSearch = false;
    private ArrayList<String> typeList;
    private List<List<String>> algorithmTypeList = new ArrayList<>();
    private List<String> dateTypeList = new ArrayList<>();
    private PopupSingleSelectFromBottom popupSelectDateType;

    private RxDialogWheelYearMonthDay mRxDialogWheelYearMonthDay;
    public SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private int filterDateStatus = 0;//0-Begin;1-End

    String QueryMode = "0";//查询模式(0:混合 ； 1：图形特征 ； 2：文字内容)
    String AlgorithmMode = "0";//算法类型（0.相同，1.近似，2.自定义）
    String FilterState = "0";//状态过滤（0.全部，1.有效，2.无效，3.待定）。
    String DateType = "0";//过滤日期（0.不过滤、1.申请日期、2.初审公告日、3.注册公告日）。
    String BeginDate = "";
    String EndDate = "";//EndDate必须大于BeginDate

    private int codeBeforeClickAlgorithm2 = 0;//在点击当前算法的自定义按钮前的状态：0-相同，1-近似

    public static void startForResult(Activity activity, boolean isSeniorSearch, ArrayList<String> typeList, int requestCode,int type) {
        Intent intent = new Intent(activity, AlgorithmSelectActivity.class);
        intent.putExtra(INTENT_KEY_IS_SENIOR_SEARCH, isSeniorSearch);
        intent.putStringArrayListExtra(INTENT_KEY_TYPE_CODE_LIST, typeList);
        intent.putExtra("type",type);
        activity.startActivityForResult(intent, requestCode);
    }

    public static void startForResult(Activity activity, boolean isSeniorSearch, ArrayList<String> typeList, int requestCode) {
        Intent intent = new Intent(activity, AlgorithmSelectActivity.class);
        intent.putExtra(INTENT_KEY_IS_SENIOR_SEARCH, isSeniorSearch);
        intent.putStringArrayListExtra(INTENT_KEY_TYPE_CODE_LIST, typeList);
        activity.startActivityForResult(intent, requestCode);
    }

    public static void startForResult(Fragment fragment, boolean isSeniorSearch, ArrayList<String> typeList, int requestCode) {
        Intent intent = new Intent(fragment.getActivity(), AlgorithmSelectActivity.class);
        intent.putExtra(INTENT_KEY_IS_SENIOR_SEARCH, isSeniorSearch);
        intent.putStringArrayListExtra(INTENT_KEY_TYPE_CODE_LIST, typeList);
        fragment.startActivityForResult(intent, requestCode);
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_algorithm_select;
    }

    @Override
    protected void onMyCreate() {
        ButterKnife.bind(this);
        showToolbar("查询算法选择");
        initData();
        initView();
        initPopupSelectDateType();
        initWheelYearMonthDayDialog();
    }

    private void initData(){
        isSeniorSearch = getIntent().getBooleanExtra(INTENT_KEY_IS_SENIOR_SEARCH, false);
        typeList = getIntent().getStringArrayListExtra(INTENT_KEY_TYPE_CODE_LIST);

        dateTypeList.add("不过滤");
        dateTypeList.add("申请日期");
        dateTypeList.add("初审公告日");
        dateTypeList.add("注册公告日");
    }

    private void initView(){
        if (getIntent().getIntExtra("type",0)==1){
            btnAlgorithmSearch.setVisibility(View.GONE);
        }
        if (isSeniorSearch){
            llQueryMode.setVisibility(View.VISIBLE);
            rgQueryMode.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                    switch (checkedId){
                        case R.id.rb_query_mode_0:
                            QueryMode = "0";
                            break;
                        case R.id.rb_query_mode_1:
                            QueryMode = "1";
                            break;
                        case R.id.rb_query_mode_2:
                            QueryMode = "2";
                            break;
                    }
                }
            });
        }

        rgAlgorithm.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId){
                    case R.id.rb_algorithm_0:
                        codeBeforeClickAlgorithm2 = 0;
                        AlgorithmMode = "0";
                        if (algorithmTypeList != null){
                            algorithmTypeList.clear();
                        }
                        break;
                    case R.id.rb_algorithm_1:
                        codeBeforeClickAlgorithm2 = 1;
                        AlgorithmMode = "1";
                        if (algorithmTypeList != null){
                            algorithmTypeList.clear();
                        }
                        break;
                    case R.id.rb_algorithm_2:
                        if (!AlgorithmMode.equals("2")){
                            AlgorithmActivity.startForResult(AlgorithmSelectActivity.this, typeList, REQUEST_CODE_SELECT_ALGORITHM_TYPE_LIST);
                        }
                        AlgorithmMode = "2";
                        break;
                }
            }
        });

        rgFilterState.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId){
                    case R.id.rb_filter_state_0:
                        FilterState = "0";
                        break;
                    case R.id.rb_filter_state_1:
                        FilterState = "1";
                        break;
                    case R.id.rb_filter_state_2:
                        FilterState = "2";
                        break;
                    case R.id.rb_filter_state_3:
                        FilterState = "3";
                        break;
                }
            }
        });
    }

    @OnClick({R.id.btn_algorithm_search, R.id.tv_filter_date_type, R.id.tv_filter_date_begin, R.id.tv_filter_date_end, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_algorithm_search:
                if (AlgorithmMode.equals("2")){
                    AlgorithmActivity.startForResult(AlgorithmSelectActivity.this, typeList, REQUEST_CODE_SELECT_ALGORITHM_TYPE_LIST);
                } else {
                    rgAlgorithm.check(R.id.rb_algorithm_2);
                }
                break;
            case R.id.tv_filter_date_type:
                popupSelectDateType.showPopupWindow();
                break;
            case R.id.tv_filter_date_begin:
                filterDate();
                filterDateStatus = 0;
                break;
            case R.id.tv_filter_date_end:
                filterDate();
                filterDateStatus = 1;
                break;
            case R.id.btn_submit:
                if (!DateType.equals("0")){
                    if (TextUtils.isEmpty(BeginDate)){
                        toastMsg("开始时间不能为空");
                    } else if (TextUtils.isEmpty(EndDate)){
                        toastMsg("结束时间不能为空");
                    } else {
                        setResultData();
                        AlgorithmSelectActivity.this.finish();
                    }
                } else {
                    setResultData();
                    AlgorithmSelectActivity.this.finish();
                }

                break;
        }
    }

    /**
     * 过滤日期（0.不过滤、1.申请日期、2.初审公告日、3.注册公告日）。
     */
    private void initPopupSelectDateType(){
        popupSelectDateType = new PopupSingleSelectFromBottom(AlgorithmSelectActivity.this, "选择过滤类型", dateTypeList);
        popupSelectDateType.setOnItemClickListener(new PopupSingleSelectFromBottom.OnItemClickListener() {
            @Override
            public void onItemClick(String item, int position) {
                tvFilterDateType.setText(item);
                DateType = position+"";
                tvFilterDateBegin.setText("");
                BeginDate = "";
                tvFilterDateEnd.setText("");
                EndDate = "";
            }
        });
    }

    private void initWheelYearMonthDayDialog() {
        // ------------------------------------------------------------------选择日期开始
        mRxDialogWheelYearMonthDay = new RxDialogWheelYearMonthDay(this, 2000, 2100);
        mRxDialogWheelYearMonthDay.getCheckBox_day().setVisibility(View.GONE);
        mRxDialogWheelYearMonthDay.getYear().setCurrentItem(17);
        mRxDialogWheelYearMonthDay.getTv_sure().setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        int year = mRxDialogWheelYearMonthDay.getSelectorYear();
                        String month = mRxDialogWheelYearMonthDay.getSelectorMonth();
                        String day = mRxDialogWheelYearMonthDay.getSelectorDay();
                        String date = year + "-" + month + "-" +day;
                        if (filterDateStatus == 0){
                            long begin = RxTimeUtils.string2Milliseconds(date, dateFormat);
                            String endStr = tvFilterDateEnd.getText().toString();
                            if (TextUtils.isEmpty(endStr)){
                                tvFilterDateBegin.setText(date);
                                BeginDate = date;
                            } else {
                                long end = RxTimeUtils.string2Milliseconds(endStr, dateFormat);
                                if (end < begin){
                                    toastMsg("开始时间必须小于或等于截止时间");
                                } else {
                                    tvFilterDateBegin.setText(date);
                                    BeginDate = date;
                                }
                            }


                        } else if (filterDateStatus == 1){
                            long begin = RxTimeUtils.string2Milliseconds(tvFilterDateBegin.getText().toString(), dateFormat);
                            long end = RxTimeUtils.string2Milliseconds(date, dateFormat);
                            if (end < begin){
                                toastMsg("截止时间必须大于或等于开始时间");
                            } else {
                                tvFilterDateEnd.setText(date);
                                EndDate = date;
                            }

                        }
                        mRxDialogWheelYearMonthDay.cancel();
                    }
                });
        mRxDialogWheelYearMonthDay.getTv_cancle().setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        mRxDialogWheelYearMonthDay.cancel();
                    }
                });
        // ------------------------------------------------------------------选择日期结束
    }

    private void filterDate(){
        if (DateType.equals("0")){
            toastMsg("该种日期类型没时间可选");
        } else {
            mRxDialogWheelYearMonthDay.show();
        }
    }

    private void setResultData(){
        Intent intent = getIntent();
        intent.putExtra(INTENT_KEY_QUERY_MODE, QueryMode);
        intent.putExtra(INTENT_KEY_ALGORITHM_MODE, AlgorithmMode);
        intent.putExtra(INTENT_KEY_ALGORITHM_TYPE_LIST, (Serializable) algorithmTypeList);
        intent.putExtra(INTENT_KEY_FILTER_STATE, FilterState);
        intent.putExtra(INTENT_KEY_DATA_TYPE, DateType);
        intent.putExtra(INTENT_KEY_BEGIN_DATA, BeginDate);
        intent.putExtra(INTENT_KEY_END_DATA, EndDate);
        setResult(Activity.RESULT_OK, intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK){
            if (requestCode == REQUEST_CODE_SELECT_ALGORITHM_TYPE_LIST){
                algorithmTypeList = (List<List<String>>) data.getSerializableExtra(INTENT_KEY_ALGORITHM_TYPE_LIST);
                LogUtils.d(algorithmTypeList);
                if (algorithmTypeList == null){
                    if (codeBeforeClickAlgorithm2 == 0){
                        rgAlgorithm.check(R.id.rb_algorithm_0);
                    } else if (codeBeforeClickAlgorithm2 == 1){
                        rgAlgorithm.check(R.id.rb_algorithm_1);
                    }
                }
            }
        }
    }
}
